﻿/*
 * 由SharpDevelop创建。
 * 用户： Admin
 * 日期: 2025/5/5
 * 时间: 4:26
 * 
 * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
 */
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Web.Script.Serialization;

namespace Visitor
{
	/// <summary>
	/// 降权玩家；查询玩家权限
	/// </summary>
	public class Visitor
	{
		public static Visitor instance = null;
		
		public BDSCSBox.DataAdapter handle = null;
		
		static Dictionary<string, string> namexuids = new Dictionary<string, string>();
		
		// 从在线列表中获取xuid
		public static string getXUID(string name)
		{
			string xuid = null;
			if (namexuids.TryGetValue(name, out xuid)) {
				return xuid;
			}
			// 重载在线列表（需要通过内部实现，暂不处理）
			return xuid;
		}
		
		// 从白名单中获取xuid
		public static string getLeftXUID(string name) {
			string wl = string.Empty;
			try {
				wl = File.ReadAllText(instance.handle.workDir + "allowlist.json");
			} catch{}
			var ser = new JavaScriptSerializer();
			if (!string.IsNullOrEmpty(wl)) {
				try {
					var wlal = ser.Deserialize<ArrayList>(wl);
					if (wlal != null && wlal.Count > 0) {
						foreach (Dictionary<string, object> d in wlal) {
							object dname;
							if (d.TryGetValue("name", out dname)) {
								if (dname.ToString() == name) {	// 找到
									object dxuid;
									if (d.TryGetValue("xuid", out dxuid)) {
										return dxuid.ToString();
									}
								}
							}
						}
					}
				}catch(Exception e){Console.WriteLine(e.StackTrace);}
			}
			return null;
		}
		
		// 查询玩家当前权限
		public static string whatperm(string xuid) {
			if (string.IsNullOrEmpty(xuid))
				return null;
			string perm = null;
			var ser = new JavaScriptSerializer();
			string sops = string.Empty;
			try {
				sops = File.ReadAllText(instance.handle.workDir + "permissions.json");
			} catch{}
			var opl = new ArrayList();
			if (!string.IsNullOrEmpty(sops)) {
				var vis = ser.Deserialize<ArrayList>(sops);
				vis = vis ?? new ArrayList();
				opl = vis;
				foreach (Dictionary<string, object> d in opl) {
					object dxuid;
					if (d.TryGetValue("xuid", out dxuid)) {
						if (dxuid.ToString() == xuid) {	// 找到
							object dperm;
							if (d.TryGetValue("permission", out dperm)) {
								perm = dperm.ToString();
							}
							break;
						}
					}
				}
			}
			return perm;
		}
		
		// 将玩家加入权限列表
		public static bool visitorPlayer(string xuid) {
			if (!string.IsNullOrEmpty(xuid)) {
				var ser = new JavaScriptSerializer();
				string sops = string.Empty;
				try {
					sops = File.ReadAllText(instance.handle.workDir + "permissions.json");
				} catch{}
				var opl = new ArrayList();
				bool finded = false;
				if (!string.IsNullOrEmpty(sops)) {
					var vis = ser.Deserialize<ArrayList>(sops);
					vis = vis ?? new ArrayList();
					opl = vis;
					foreach (Dictionary<string, object> d in opl) {
						object dxuid;
						if (d.TryGetValue("xuid", out dxuid)) {
							if (dxuid.ToString() == xuid) {	// 找到
								d["permission"] = "visitor";
								finded = true;
								break;
							}
						}
					}
				}
				if (!finded) {	// 装入新权限
					var nd = new Dictionary<string, object>();
					nd["permission"] = "visitor";
					nd["xuid"] = xuid;
					opl.Add(nd);
				}
				try {
					File.WriteAllText(instance.handle.workDir + "permissions.json", ser.Serialize(opl));
					if (instance != null)
						instance.handle.sendMsg("permission reload");	// 重载权限配置
					return true;
				} catch{}
			}
			return false;
		}
		
		// 发送一个tellraw
		// 需要前置插件：saych
		// 需要配合AddonJs：runchcmd
		public static void tellraw(string pname, string msg) {
			var ser = new JavaScriptSerializer();
			var rawtxt = new Dictionary<string, object>();
			var rawtext = new ArrayList();
			var text = new Dictionary<string, object>();
			text["text"] = msg;
			rawtext.Add(text);
			rawtxt["rawtext"] = rawtext;
			if (instance != null) {
				string chcmd = "tellraw \"" + pname + "\" " + ser.Serialize(rawtxt);
				var b = new {
				id = "command",
				msg = chcmd
				};
				string chmsg = ser.Serialize(b);
				instance.handle.sendMsg("saych " + chmsg);
			}
		}
		
		private Visitor(BDSCSBox.DataAdapter h) {
			this.handle = h;
			
			BDSCSBox.TYPES.F_FUNC onsend = (cmd) => {
				string scmd = cmd.Trim();
				if (scmd.ToLower().IndexOf("visitor") == 0) {	// 可能找到
					string[] cmds = scmd.Split(' ');
					if (cmds[0].ToLower() == "visitor") {	// 找到
						if (cmds.Length > 1) {
							string pname = scmd.Substring(7).Trim().Trim('"');
							string xuid = null;
							if (!string.IsNullOrEmpty(xuid = getXUID(pname))) {
								// 在线降权
								if (visitorPlayer(xuid)) {
									//tellraw(pname, "您已被降级权限为访客。");
									Console.WriteLine("[Visitor] Visited : " + pname);
									return false;
								}
							} else if (!string.IsNullOrEmpty(xuid = getLeftXUID(pname))) {
								// 离线降权
								if (visitorPlayer(xuid)) {
									Console.WriteLine("[Visitor] 玩家 " + pname + " 已被降级权限为访客。");
									return false;
								}
							} else {
								Console.WriteLine("[Visitor] 未能找到对应玩家。");
							}
						} else {
							Console.WriteLine("[Vistor] 参数过少。用法：visitor [playername]");
						}
						return false;
					}
				} else if (scmd.ToLower().IndexOf("whatop") == 0) {		// 查询指令，通过套接字whatop:info回传玩家权限信息
					string[] cmds = scmd.Split(' ');
					if (cmds[0].ToLower() == "whatop") {	// 找到
						if (cmds.Length > 1) {
							string pname = scmd.Substring(6).Trim().Trim('"');
							string pxuid = null;
							string pperm = null;
							if (string.IsNullOrEmpty(pxuid = getXUID(pname))) {
								pxuid = getLeftXUID(pname);
							}
							if (!string.IsNullOrEmpty(pxuid)) {
								pperm = whatperm(pxuid);
							}
							var b = new {
								name = pname,
								xuid = pxuid,
								perm = pperm
							};
							var pinfo = (new JavaScriptSerializer()).Serialize(b);
							instance.handle.sendMsg("scriptevent whatop:info " + pinfo);
						} else {
							Console.WriteLine("[Whatop] 参数过少。用法：whatop [playername]");
						}
						return false;
					}
				}
				return true;
			};
			handle.addDataSender(onsend);
			
			BDSCSBox.TYPES.F_FUNC onreceive = (msg) => {
				int i = msg.IndexOf("INFO] Player connected:");
				if (i > 0) {
					var pandx = msg.Substring(i+5);
					var pxs = pandx.Split(',');
					if (pxs.Length == 2) {
						var ps = pxs[0].Split(':');
						var xs = pxs[1].Split(':');
						if (ps.Length == 2 && xs.Length == 2) {
							namexuids[ps[1].Trim()] = xs[1].Trim();
						}
					}
				}
				return true;
			};
			handle.addDataReceiver(onreceive);
		}
		
		public static void getInstance(BDSCSBox.DataAdapter h) {
			instance = instance ?? new Visitor(h);
		}
	}
}

namespace BDSCSBox {
	public class CSL {
		public bool onStart(BDSCSBox.DataAdapter handle) {	// dll入口，注册所有函数
			Visitor.Visitor.getInstance(handle);
			Console.WriteLine("[Visitor] 降权指令visitor、查询指令whatop已加载。");
			return true;
		}
	}
}